package cn.glc.daily.life.config.shiro.realm;

import cn.glc.daily.life.common.exceptions.GlobalException;
import cn.glc.daily.life.common.utils.JwtUtils;
import cn.glc.daily.life.config.shiro.token.JwtToken;
import cn.glc.daily.life.model.to.PermissionTo;
import cn.glc.daily.life.model.to.RolePermissionTo;
import cn.glc.daily.life.model.vo.jwt.auth.JwtUserDetailVo;
import cn.glc.daily.life.model.vo.user.UserVo;
import cn.glc.daily.life.web.service.user.RolePermissionService;
import cn.glc.daily.life.web.service.user.UserService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.glc.daily.life.common.enums.GlobalCodeEnum.BusinessExceptionEnum.LOGIN_FAIL;

/**
 * @author simon
 * @date 2020/9/20 16:43
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
public class JwtTokenRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录用户名
        JwtUserDetailVo jwtUserDetailVo = JwtUtils.getUserInfo(String.valueOf(principalCollection.getPrimaryPrincipal()));
        // 查询用户名称
        UserVo userVo = userService.findDetailsByUid(jwtUserDetailVo.getUid());
        // 添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        userVo.getUserRoleToList().forEach(userRoleTo -> {
            RolePermissionTo rolePermissionTo = rolePermissionService.findAllByRoleId(userRoleTo.getRoleId());
            simpleAuthorizationInfo.addRole(rolePermissionTo.getRoleCode());
            Set<String> perms = rolePermissionTo.getPermissionToList().stream().map(PermissionTo::getPerms).collect(Collectors.toSet());
            simpleAuthorizationInfo.addStringPermissions(perms);
        });
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token = (JwtToken) authenticationToken;
        JwtUserDetailVo jwtUserDetailVo = JwtUtils.getUserInfo(String.valueOf(token.getPrincipal()));
        UserVo userVo = Optional.of(userService.findDetailsByUid(jwtUserDetailVo.getUid())).orElseThrow(() -> new GlobalException(LOGIN_FAIL));
        String jwt = JSON.toJSONString(jwtUserDetailVo);
        //有一个能认证成功就ok
        if (userVo.getUserAuthsToList().stream().filter(userAuthsTo -> JwtUtils.verify(String.valueOf(token.getPrincipal()), jwt, userAuthsTo.getCredential())).anyMatch(userAuthsTo -> true)) {
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(token.getPrincipal(), token.getPrincipal(), getName());
            return simpleAuthenticationInfo;
        } else {
            Exception errors = JwtUtils.getErrors(jwt);
            if (Objects.nonNull(errors)) {
                log.error("用户:{},校验异常:{}", jwt, errors);
            }
            return null;
        }
    }
}
